import React, { useEffect, useRef } from "react";
import * as d3 from "d3";

const unemployment = [
  {
    division: "Bethesda-Rockville-Frederick, MD Met Div",
    date: "2000-01-01",
    unemployment: 2.6,
  },
  {
    division: "Bethesda-Rockville-Frederick, MD Met Div",
    date: "2000-02-01",
    unemployment: 2.6,
  },
  {
    division: "Bethesda-Rockville-Frederick, MD Met Div",
    date: "2000-03-01",
    unemployment: 2.6,
  },
  {
    division: "Bethesda-Rockville-Frederick, MD Met Div",
    date: "2000-04-01",
    unemployment: 2.6,
  },
  {
    division: "Bethesda-Rockville-Frederick, MD Met Div",
    date: "2000-05-01",
    unemployment: 2.7,
  },
  {
    division: "Bethesda-Rockville-Frederick, MD Met Div",
    date: "2000-06-01",
    unemployment: 2.7,
  },
  {
    division: "Bethesda-Rockville-Frederick, MD Met Div",
    date: "2000-07-01",
    unemployment: 2.7,
  },
  {
    division: "Bethesda-Rockville-Frederick, MD Met Div",
    date: "2000-08-01",
    unemployment: 2.6,
  },
  {
    division: "Bethesda-Rockville-Frederick, MD Met Div",
    date: "2000-09-01",
    unemployment: 2.6,
  },
  {
    division: "Bethesda-Rockville-Frederick, MD Met Div",
    date: "2000-10-01",
    unemployment: 2.6,
  },
  {
    division: "Bethesda-Rockville-Frederick, MD Met Div",
    date: "2000-11-01",
    unemployment: 2.6,
  },
  {
    division: "Bethesda-Rockville-Frederick, MD Met Div",
    date: "2000-12-01",
    unemployment: 2.6,
  },
  {
    division: "Bethesda-Rockville-Frederick, ND Met Div",
    date: "2000-01-01",
    unemployment: 2.7,
  },
  {
    division: "Bethesda-Rockville-Frederick, ND Met Div",
    date: "2000-02-01",
    unemployment: 2.7,
  },
  {
    division: "Bethesda-Rockville-Frederick, ND Met Div",
    date: "2000-03-01",
    unemployment: 2.8,
  },
  {
    division: "Bethesda-Rockville-Frederick, ND Met Div",
    date: "2000-04-01",
    unemployment: 2.8,
  },
  {
    division: "Bethesda-Rockville-Frederick, ND Met Div",
    date: "2000-05-01",
    unemployment: 2.9,
  },
  {
    division: "Bethesda-Rockville-Frederick, ND Met Div",
    date: "2000-06-01",
    unemployment: 3,
  },
  {
    division: "Bethesda-Rockville-Frederick, ND Met Div",
    date: "2000-07-01",
    unemployment: 3.1,
  },
  {
    division: "Bethesda-Rockville-Frederick, ND Met Div",
    date: "2000-08-01",
    unemployment: 3.3,
  },
];

const UnemploymentChart = () => {
  const svgRef = useRef();

  useEffect(() => {
    // 将数据中的日期解析为 Date 对象
    const data = unemployment.map((d) => ({
      ...d,
      date: new Date(d.date),
    }));

    // 设置图表的尺寸
    const margin = { top: 20, right: 50, bottom: 50, left: 50 };
    const width = 800 - margin.left - margin.right;
    const height = 400 - margin.top - margin.bottom;

    // 创建 SVG 画布
    const svg = d3
      .select(svgRef.current)
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
      .append("g")
      .attr("transform", `translate(${margin.left},${margin.top})`);

    // 创建缩放比例
    const xScale = d3
      .scaleTime()
      .domain(d3.extent(data, (d) => d.date))
      .range([0, width]);

    const yScale = d3
      .scaleLinear()
      .domain([
        d3.min(data, (d) => d.unemployment) - 0.5,
        d3.max(data, (d) => d.unemployment) + 0.5,
      ])
      .range([height, 0]);

    // 创建颜色比例（根据 division 变化）
    const colorScale = d3
      .scaleOrdinal()
      .domain([...new Set(data.map((d) => d.division))])
      .range(d3.schemeCategory10);

    // 定义 x 和 y 轴
    const xAxis = d3.axisBottom(xScale).tickFormat(d3.timeFormat("%Y-%m"));
    const yAxis = d3.axisLeft(yScale);

    // 添加 x 和 y 轴到 SVG
    svg
      .append("g")
      .attr("class", "x axis")
      .attr("transform", `translate(0,${height})`)
      .call(xAxis)
      .selectAll("text")
      .attr("transform", "rotate(-45)")
      .style("text-anchor", "end");

    svg.append("g").attr("class", "y axis").call(yAxis);

    // 按 division 分组数据
    const dataNest = d3.groups(data, (d) => d.division);

    // 绘制折线
    const line = d3
      .line()
      .x((d: any) => xScale(d.date))
      .y((d: any) => yScale(d.unemployment));

    dataNest.forEach(function ([key, values]) {
      svg
        .append("path")
        .datum(values)
        .attr("class", "line")
        .attr("d", line as any)
        .attr("stroke", colorScale(key) as any)
        .attr("stroke-width", 2)
        .attr("fill", "none");
    });

    // 添加图例
    const legend = svg
      .selectAll(".legend")
      .data(dataNest)
      .enter()
      .append("g")
      .attr("class", "legend")
      .attr("transform", (d, i) => `translate(50, ${i * 20})`);

    legend
      .append("rect")
      .attr("x", width - 10)
      .attr("width", 10)
      .attr("height", 10)
      .style("fill", (d) => colorScale(d[0]) as any);

    legend
      .append("text")
      .attr("x", width - 20)
      .attr("y", 9)
      .attr("dy", ".35em")
      .style("text-anchor", "end")
      .text((d) => d[0]);

    // 清除副作用
    return () => {
      d3.select(svgRef.current).selectAll("*").remove();
    };
  }, []);

  return (
    <div>
      <h1>Unemployment Rate by Division</h1>
      <svg ref={svgRef}></svg>
    </div>
  );
};

export default UnemploymentChart;
